-- upgrade_third_hand
-- Created by dengc
-- 成就：升级第三只手

-- 内部函数声明
local whenUpgrade;

-- 关注事件
EventMgr.register("achievements/upgrade_third_hand", event.UPGRADE_SPECIAL_EQUIP, function(args)
    whenUpgrade(args);
end);

-- 激活事件的回调
whenUpgrade = function(args)
    local pos     = args["pos"];
    local classId = args["classId"];

    -- 玩家不在地牢中
    if not DungeonM.isInDungeon() then
        return;
    end

    -- 不是第三只手
    local thirdHandId = FormulaM.invoke("THIRD_HAND_CLASS_ID");
    if classId ~= thirdHandId then
        return;
    end

    -- 获取当前装备已升级到的等级
    local level = EquipM.getSpecialEquipLevel(classId);
    level = level >= 1 and level or 1; 

    -- 获取当前所在的地牢区域
    local area = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("upgrade_third_hand");

    for _, id in pairs(ids) do
        -- 已经完成了
        if true == AchievementM.isCompleted(id) then
            return;
        end

        -- 不是该迷宫的成就
        if not AchievementM.isBelongTo(id, area) then
            return;
        end

        -- 获取参数配置
        local ruleArgs = AchievementM.query(id, "rule_arg");
        local needArgs = ruleArgs["args"];

        -- 判断是否满足条件
        if level < needArgs then
            return;
        end

        -- 尝试完成成就
        AchievementM.tryComplete(id, 1);
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = AchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local value   = ruleArg["args"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{0}", value);

        return desc;
    end,
};
